package com.yzmoney.wechat.service;


import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.constant.PropertyUtils;
import com.yzmoney.common.util.HttpClientUtil;
import com.yzmoney.common.util.JDKStackTrace;
import com.yzmoney.wechat.model.token.AuthUserInfoJson;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信用户服务(这里与auth2.0获取用户信息的方法有所区别)
 */
@Component
public class WechatUserService {

    private static Logger logger = Logger.getLogger(WechatUserService.class);

    private static String baseUserInfoUrl = PropertyUtils.getValue("USERINFOURL", "", Constants.GZH_PATH);

    public WechatUserService() {
        super();
    }

    @Autowired
    private WechatAccessTokenService wechatAccessTokenService;

    /**
     * 通过openId 获取用户信息
     *
     * @param openId
     * @return
     */
    public AuthUserInfoJson loadWechatUserInfo(String openId) {
        try {
            String access_token = wechatAccessTokenService.getGZHAccessToken();
            String url = getUserInfoUrl(access_token, openId);
            String replyJsonStr = HttpClientUtil.get(url,null,null);
            logger.info("----->>>url=" + url + ",replyJsonStr=" + replyJsonStr);
            JSONObject jsonObject = JSONObject.fromObject(replyJsonStr);
            String openid = (String) jsonObject.get("openid");
            String nickname = (String) jsonObject.get("nickname");
            String headimgurl = (String) jsonObject.get("headimgurl");
            String unionid = (String) jsonObject.get("unionid");
            if (StringUtils.isNotEmpty(openid)) {
                AuthUserInfoJson userInfo = new AuthUserInfoJson(openid, nickname, headimgurl, unionid);
                return userInfo;
            }
        } catch (Exception e) {
            logger.warn("通过openId获取用户信息错误，openId：" + openId + JDKStackTrace.getJDKStrack(e));
        }

        return null;
    }

    /**
     * 拼接公众号 获取用户信息Url
     *
     * @return
     */
    private static String getUserInfoUrl(String access_token, String openId) {
        String userInfoUrl = baseUserInfoUrl
                + access_token
                + "&openid=" + openId
                + "&lang=zh_CN";
        return userInfoUrl;
    }

}
